package com.mapler.autoresponder.ui;

import com.mapler.ui.*;
import com.mapler.utility.HttpHelper;
import com.mapler.utility.IConstant;
import java.awt.Color;
import java.io.File;
import java.io.FileInputStream;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Iterator;
import java.util.Locale;
import javax.swing.JFileChooser;
import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.DataFormatter;
import org.apache.poi.ss.usermodel.Row;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;

/**
 *
 * @author none
 */
public class AccAutoResponderImpUI extends javax.swing.JPanel {

    private static Logger log = Logger.getLogger(AddSettingUI.class);
    private String username;
    private String password;
    private String country;

    /**
     * Creates new form AdImpUI
     */
    public AccAutoResponderImpUI() {
        initComponents();
    }

    public AccAutoResponderImpUI(String username, String password, String country) {
        this.username = username;
        this.password = password;
        this.country = country;
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        message = new javax.swing.JLabel();
        jTFile = new javax.swing.JTextField();
        jBFileSelector = new javax.swing.JButton();
        jBImport = new javax.swing.JButton();
        jCBIsHeader = new javax.swing.JCheckBox();
        jLabel1 = new javax.swing.JLabel();

        message.setText("Message");

        jBFileSelector.setText("Select file...");
        jBFileSelector.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBFileSelectorActionPerformed(evt);
            }
        });

        jBImport.setText("Import");
        jBImport.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBImportActionPerformed(evt);
            }
        });

        jCBIsHeader.setText("Is Header");

        jLabel1.setText("AutoResponder");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(message, javax.swing.GroupLayout.PREFERRED_SIZE, 445, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jBImport)
                            .addComponent(jTFile, javax.swing.GroupLayout.PREFERRED_SIZE, 340, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jBFileSelector))
                    .addComponent(jCBIsHeader)
                    .addComponent(jLabel1))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jLabel1)
                .addGap(64, 64, 64)
                .addComponent(message, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(31, 31, 31)
                .addComponent(jCBIsHeader)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jTFile, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jBFileSelector))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jBImport)
                .addContainerGap(143, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents

    public void clearFields() {
        try {
            jCBIsHeader.setSelected(false);
            jTFile.setText("");
            message.setText("");
        } catch (Throwable ex) {
            log.debug("clearFields:: Error causes " + ex);
        }
    }

    private void jBFileSelectorActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBFileSelectorActionPerformed
        try {
            JFileChooser fc = new JFileChooser();
            fc.addChoosableFileFilter(new OnlyExt());

            int returnval = fc.showOpenDialog(null);
            if (returnval == JFileChooser.APPROVE_OPTION) {
                File file = fc.getSelectedFile();
                jTFile.setText(file.getPath());
            }
        } catch (Throwable ex) {
            message.setText("Error " + ex.getMessage());
            log.debug("Error " + ex);
        }
    }//GEN-LAST:event_jBFileSelectorActionPerformed

    private void jBImportActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBImportActionPerformed
        try {
            if (jTFile.getText().isEmpty()) {
                return;
            }
            FileInputStream file = new FileInputStream(jTFile.getText());
            HSSFWorkbook workbook = new HSSFWorkbook(file);
            HSSFSheet sheet = workbook.getSheetAt(0);
            Iterator<Row> rowIterator = sheet.iterator();
            boolean isHeader = jCBIsHeader.isSelected();
            int successc = 0;
            int failc = 0;
            DataFormatter formatter = new DataFormatter(Locale.US);
            while (rowIterator.hasNext()) {
                Row row = rowIterator.next();
                if (isHeader) {
                    isHeader = false;
                    continue;
                }

                StringBuilder request = new StringBuilder();
                request.append("<Request>");
                request.append("<username>").append(this.username).append("</username>");
                request.append("<password>").append(this.password).append("</password>");

                if (row.getCell(0) != null) {
                    request.append("<server>").append(row.getCell(0)).append("</server>");
                } else {
                    request.append("<server>").append("").append("</server>");
                }

                if (row.getCell(1) != null) {
                    request.append("<port>").append(row.getCell(1)).append("</port>");
                } else {
                    request.append("<port>").append("").append("</port>");
                }

                if (row.getCell(2) != null) {
                    request.append("<ssl>").append(row.getCell(2)).append("</ssl>");
                } else {
                    request.append("<ssl>").append("").append("</ssl>");
                }

                if (row.getCell(3) != null) {
                    request.append("<username>").append(row.getCell(3)).append("</username>");
                } else {
                    request.append("<username>").append("").append("</username>");
                }

                if (row.getCell(4) != null) {
                    request.append("<password>").append(formatter.formatCellValue(row.getCell(4))).append("</password>");
                } else {
                    request.append("<password>").append(0).append("</password>");
                }

                if (row.getCell(5) != null) {
                    request.append("<reply_email>").append(row.getCell(5)).append("</reply_email>");
                } else {
                    request.append("<reply_email>").append("").append("</reply_email>");
                }
                
                request.append("<working>").append(0).append("</working>");
                request.append("<serial>").append(0).append("</serial>");
                request.append("<ud_value1>").append(0).append("</ud_value1>");
                request.append("</Request>");

                String req = URLEncoder.encode(request.toString(), "UTF-8");
                String uri = "http://" + IConstant.HOSTNAME + "/index.php?r=autoresponderAccount/addAccount";
                String param = "request=" + req;
                String response = HttpHelper.post(new URL(uri), param);

                Document document = DocumentHelper.parseText(response);
                String errorCode = document.valueOf("Response/errorcode");
                String msg = document.valueOf("Response/message");
                if (errorCode.equalsIgnoreCase("000")) {
                    failc++;
                    this.message.setBackground(Color.red);
                } else {
                    successc++;
                    this.message.setBackground(Color.black);
                }
                this.message.setText(msg);
            }
            int tCount = successc + failc;
            String msg = "Total record:" + tCount + " successfully imported:" + successc + " failed:" + failc;
            this.message.setText(msg);
        } catch (Throwable ex) {
            message.setText("Error " + ex.getMessage());
            log.debug("Error " + ex);
        }
    }//GEN-LAST:event_jBImportActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jBFileSelector;
    private javax.swing.JButton jBImport;
    private javax.swing.JCheckBox jCBIsHeader;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JTextField jTFile;
    private javax.swing.JLabel message;
    // End of variables declaration//GEN-END:variables
}
